#pragma once
#include <iostream>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
namespace client
{
    using namespace std;
    enum
    {
        USAGE_ERROR = 0,
        SOCKET_ERROR,
        BIND_ERROR
    };

    class tcpclient
    {

    public:
        tcpclient(const string &ip, const uint16_t port)
            : _sockfd(-1), _serverip(ip), _serverport(port)
        {
        }
        void initClient()
        {

            // 1.跟udp一样 首先进行socket设置
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                cout << "SOCKET error" << endl;
                exit(SOCKET_ERROR);
            }
            cout << "SOCKET success" << endl;
            // 2. tcp的客户端要不要bind？要的！ 要不要显示的bind？不要！这里尤其是client port要让OS自定随机指定！
            // 3. 要不要listen？不要！
            // 4. 要不要accept? 不要！
            // 5. 要什么呢？？要发起链接
        }
        void run()
        {

            // 这里需要connect链接
            struct sockaddr_in peer;
            bzero(&peer, sizeof(peer));
            peer.sin_family = AF_INET;
            peer.sin_port = htons(_serverport);
            peer.sin_addr.s_addr = inet_addr(_serverip.c_str());
            if (connect(_sockfd, (struct sockaddr *)&peer, sizeof(peer)) != 0)
            {
                cerr << "socket connect error" << endl;
            }
            else
            {
                string message;
                for (;;)
                {
                    cout << "[please enter#]";
                    getline(cin, message);
                    write(_sockfd, message.c_str(), message.size());

                    // 说明数据发送过去了
                    char buffer[1024];
                    int number = read(_sockfd, buffer, sizeof(buffer)-1);
                    if (number > 0)
                    {
                        buffer[number]=0;  //将末尾置为0
                        message = "[sever back]"+message;
                        cout << message << endl;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
        ~tcpclient() {}

    private:
        int _sockfd;
        string _serverip;
        uint16_t _serverport;
    };
}